package twi;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;

import twi.query.SparqlQuery;
import twi.result.QueryResult;

import jtools.files.TextFile;

import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.impl.IndividualImpl;
import com.hp.hpl.jena.ontology.impl.OntModelImpl;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;

public class OWLModel extends OntModelImpl {

	
	public static void main(String[] arg) throws IOException{
		String sparql = " SELECT ?sub ?pre ?obj \n WHERE { ?sub ?pre ?obj. } ";
		OWLModel model = OWLModel.readOWLFile(new File("TWI6.owl"));
		model.add((Statement)null);
		SparqlQuery query = new SparqlQuery(sparql, model);
		QueryResult qrs = QueryManager.executeQuery(query);
		String[] title = qrs.asTable().getTitleRow();
		for (int i = 0; i < title.length; i++)
			System.out.print(title[i] + "  |  ");
		System.out.println();
		String[][] val = qrs.asTable().getValues(true);
		for (int i = 0; i < val.length; i++){
			for (int j = 0; j < val[i].length; j++)
				System.out.print(val[i][j] + "  |  ");
			System.out.println();
		}
	}
	
	
	private String 	basePrefix = null;
	private File	baseFile = null;
	
	private OWLModel(OntModelSpec spec) {
		super(spec);
	}
	private OWLModel(OntModelSpec spec, Model model) {
		super(spec, model);
	}
	public static OWLModel readOWLFile(File file) throws IOException{
		String uri = null;
		TextFile tf = new TextFile();
		tf.readFile(file, false);
		while (tf.hasNext()) {
			String line = tf.getNextLine();
			if (line.contains("xml:base=\"http:")) {
				uri = line.replace(">", "");
				uri = uri.replace("xml:base=", "");
				uri = uri.replace("\"", "");
				uri = uri.replace(" ", "");
				break;
			}
		}
		tf.closeFile();
		if (uri == null) {
			throw new IOException("Could not find base URI");
		}
		OWLModel ontologyModel = new OWLModel(OntModelSpec.OWL_MEM, null);
		
		try {
			ontologyModel.getDocumentManager().addAltEntry(uri,
					file.toURI().toURL().toString());
			ontologyModel.read(uri);
			ontologyModel.setBasePrefix(uri);
			ontologyModel.setBaseFile(file);
		} catch (MalformedURLException e) {
			throw new IOException(e);
		}
		return ontologyModel;
	}



	private void setBaseFile(File file) {
		this.baseFile = file;
	}

	public String getBasePrefix() {
		return basePrefix;
	}

	public void setBasePrefix(String basePrefix) {
		if (basePrefix.endsWith("#"))
			this.basePrefix = basePrefix;
		else
			this.basePrefix = basePrefix + "#";
	}
}
